package com.qianfeng.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.model.Dept;
import com.qianfeng.service.DeptService;
import com.qianfeng.tkMapper.DeptMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Transactional
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    public PageInfo<Dept> findPage(Dept param, Integer page, Integer rows) {
        //创建一个保存查询条件的对象
        Example example = new Example(Dept.class);

        if (param != null) {
            Example.Criteria and = example.and();
            //拼接 部门名称进行模糊查询的条件
            if (StringUtils.isNotBlank(param.getDname())) {
                and.andLike("dname", "%" + param.getDname() + "%");
            }
            //拼接 部门ID 等值查询的条件
            if (param.getId() != null) {
                and.andEqualTo("id", param.getId());
            }
            //拼接 部门的描述的模糊查询条件
            if (StringUtils.isNotBlank(param.getLoc())) {
                and.andLike("loc", "%" + param.getLoc() + "%");
            }
        }

        //调用pagehelper全局静态方法，设置分页条件
        PageHelper.startPage(page, rows);
        List<Dept> depts = deptMapper.selectByExample(example);


        return new PageInfo<Dept>(depts);
    }

    public void save(Dept dept) {
        if (dept.getId() != null) {
            deptMapper.updateByPrimaryKey(dept);
        } else {
            deptMapper.insert(dept);
        }
    }

    public boolean delById(Integer id) {
        return deptMapper.deleteByPrimaryKey(id) > 0;
    }
}
